package controller.servlet.product;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.Category;
import model.Product;
import controller.dao.Dao_Category;
import controller.dao.Dao_Product;

public class editProduct extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int codigo = Integer.parseInt(request.getParameter("cod"));
		Dao_Category daocat = new Dao_Category();
		List<Category> category = daocat.listAll();
		Dao_Product daoe = new Dao_Product();
		Product p = daoe.list(codigo);
		request.setAttribute("prod", p);
		List<Category> categories = p.getCategories();
//		for (int i = 0; i<p.getCategories().size(); i++){
//			categories.add(p.getCategories().get(i).getName());
//		}
		request.setAttribute("category", category);
		request.setAttribute("categories", categories);
		RequestDispatcher rd = request.getRequestDispatcher("/admin/register-product.jsp");
		rd.forward(request, response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		Dao_Product daoe = new Dao_Product();
		int codigo = Integer.parseInt(request.getParameter("cod"));
		String name = request.getParameter("name");
		double price = Double.parseDouble(request.getParameter("price"));
		String description = request.getParameter("description");
		int stock = Integer.parseInt(request.getParameter("stock"));
		List<Category> categories = new ArrayList<Category>();
		Dao_Category daoCat = new Dao_Category();
		
		List<Integer> cats = new ArrayList<Integer>();
		
		String[] category = request.getParameterValues("category");
		
		for(int i=0; i<category.length; i++)
			cats.add(Integer.parseInt(category[i]));
		Category categs;
		for(int j=0;j<cats.size();j++){
			categs = daoCat.list(cats.get(j));
			categories.add(categs);
		}
		Product p = daoe.list(codigo);
		p.setCategories(categories);
		p.setDescription(description);
		p.setPrice(price);
		p.setName(name);
		p.setStock(stock);
		daoe.save(p);
		response.sendRedirect("/ShoppingCart.Com_V6/admin/product.ja");
		
	}

}
